//
//  PS_CDViewController.m
//  PolicySystem
//
//  Created by 丹丹 on 2018/11/30.
//  Copyright © 2018年 xuezi. All rights reserved.
//

#import "PS_CDViewController.h"
#import "XJ_PopUpView.h"
#import "TZImagePickerController.h"
#import "PS_PhotoView.h"
@interface PS_CDViewController ()<popViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate,photoViewDelegate,SDPhotoBrowserDelegate>
{
    NSArray * periodArr;
    NSArray * cityArr;
    NSString * cId;
    NSString * PerId;
    NSInteger isFirst;//1全款车2贷款车
    NSString * stateStr;//当前抵押类型
    //照片选择器
    TZImagePickerController *imagePickerVc;
    UIButton *addBut;
    NSString * telephoneString;
}
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *height_backView;
@property (strong, nonatomic) IBOutlet UILabel *phoneLable;
@property (strong, nonatomic) IBOutlet UIScrollView *myScroll;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *y_ScrollView;

@property (strong, nonatomic) IBOutlet UILabel *cityLabel;
@property (strong, nonatomic) IBOutlet UIImageView *c_rightArrow;
@property (strong, nonatomic) IBOutlet UITextField *jieKuanRenNameTF;
@property (strong, nonatomic) IBOutlet UITextField *cardIDTF;
@property (strong, nonatomic) IBOutlet UITextField *carOldTF;
@property (strong, nonatomic) IBOutlet UITextField *moneyTF;
@property (strong, nonatomic) IBOutlet UITextField *periodTF;

@property (strong, nonatomic) IBOutlet UITextField *phoneTF;
@property (strong, nonatomic) IBOutlet UITextField *beiZhuTF;

@property (strong, nonatomic) IBOutlet UIView *picView;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *height_picView;

@property(nonatomic,strong)NSMutableArray * imageArray;
@property(nonatomic,strong)NSMutableArray * imageUrlArray;

@property (strong, nonatomic)NSMutableArray * cityNameArray;
@property (strong, nonatomic)NSMutableArray * cityIdArray;
@property (strong, nonatomic)NSMutableArray * periodArray;
@property (strong, nonatomic)NSMutableArray * periodIdArray;
@property(nonatomic,strong) UIImagePickerController *imagePicker; //声明全局
@property (strong, nonatomic) IBOutlet UILabel *productNameLabel;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *trailing_CityLabel;

@property (strong, nonatomic) IBOutlet UIButton *quanKuanBtn;
@property (strong, nonatomic) IBOutlet UIButton *daiKuanBtn;
@property (strong, nonatomic)NSMutableArray * telephoneArray;

@property (strong, nonatomic) IBOutlet UILabel *remarkLabel;


@end

@implementation PS_CDViewController

- (NSMutableArray *)telephoneArray{
    
    if (_telephoneArray == nil) {
        
        _telephoneArray = [NSMutableArray array];
    }
    return _telephoneArray;
}


- (NSMutableArray *)periodArray{
    
    if (_periodArray == nil) {
        
        _periodArray = [NSMutableArray array];
        
    }
    return _periodArray;
}

-(NSMutableArray *)periodIdArray{
    
    if (_periodIdArray == nil) {
        
        _periodIdArray = [NSMutableArray array];
    }
    
    return _periodIdArray;
}
- (NSMutableArray *)imageUrlArray{
    
    if (_imageUrlArray == nil) {
        
        _imageUrlArray = [NSMutableArray array];
    }
    
    return _imageUrlArray;
}
- (NSMutableArray *)imageArray{
    
    if (_imageArray == nil) {
        
        _imageArray = [NSMutableArray array];
        
    }
    
    return _imageArray;
}

- (NSMutableArray *)cityIdArray{
    
    if (_cityIdArray == nil) {
        
        _cityIdArray = [NSMutableArray array];
    }
    
    return _cityIdArray;
}

- (NSMutableArray *)cityNameArray{
    
    if (_cityNameArray == nil) {
        
        _cityNameArray = [NSMutableArray array];
    }
    
    return _cityNameArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nav_titleLabel.text = @"车辆贷款";
    self.view.backgroundColor = RGBCOLOR(238, 238, 238);
    _y_ScrollView.constant = SafeAreaTopHeight;
    _height_picView.constant = 50+(SCREEN_WIDTH - 80)/3;
    _productNameLabel.text = _proName;
    isFirst = 0;
    stateStr = @"";
    [self getSubProductData];
    
    [_phoneTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self loadPic];
    [self changePic];
    // Do any additional setup after loading the view from its nib.
}
- (IBAction)getCity:(id)sender {
    
    if (self.cityNameArray.count>1) {
        
        XJ_PopUpView * popView = [[XJ_PopUpView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andTableCellWidth:230 andCellCount:self.cityNameArray.count];
        
        popView.cellArray = self.cityNameArray;
        popView.delegate = self;
        popView.type = 0;
        [self.view addSubview:popView];
    }
}

- (IBAction)getType:(id)sender {
    
    if (self.periodArray.count>0) {
        
        XJ_PopUpView * popView = [[XJ_PopUpView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andTableCellWidth:230 andCellCount:self.periodArray.count];
        
        popView.cellArray = self.periodArray;
        popView.delegate = self;
        popView.type = 1;
        [self.view addSubview:popView];
    }
    
}
- (IBAction)submitFromData:(id)sender {
    
    if (_cityLabel.text.length == 0) {
        
        [MBProgressHUD showError:@"请选择借款人所在地" toView:self.view];
        return;
    }
    
    if (_jieKuanRenNameTF.text.length == 0) {
        
        [MBProgressHUD showError:@"请输入借款人姓名" toView:self.view];
        return;
    }
    
    if (_phoneTF.text.length == 0) {
        
        [MBProgressHUD showError:@"请输入提交人联系电话" toView:self.view];
        return;
    }
    if (_phoneTF.text.length <11) {
        
        [MBProgressHUD showError:@"请正确输入提交人联系电话" toView:self.view];
        return;
    }
    
    
    NSMutableDictionary * parmDic = [NSMutableDictionary dictionary];
    [parmDic setValue:@"12" forKey:@"pid"];
    [parmDic setValue:USERID forKey:@"uid"];
    [parmDic setValue:_subPID forKey:@"sub_pid"];
    [parmDic setValue:cId forKey:@"city"];
    [parmDic setValue:_jieKuanRenNameTF.text forKey:@"name"];
    [parmDic setValue:stateStr forKey:@"type"];
    [parmDic setValue:_cardIDTF.text forKey:@"car_vehicle"];
    [parmDic setValue:_carOldTF.text forKey:@"vehicle_age"];
    [parmDic setValue:_moneyTF.text forKey:@"money"];
    [parmDic setValue:_periodTF.text forKey:@"period"];
    [parmDic setValue:_phoneTF.text forKey:@"mobile"];
    [parmDic setValue:_beiZhuTF.text forKey:@"remarks"];
    [parmDic setValue:self.imageUrlArray forKey:@"image"];
    
    
    [Utils post:APPLYSUB parameters:parmDic success:^(NSInteger recode, id jsonObject) {
        
        [MBProgressHUD showSuccess:@"申请成功" toView:self.view];
        
        int64_t delayInSeconds = 2.0; // 延迟的时间
        /*
         *  delta:
         *
         *  @parameter 1.时间参照，从此刻开始计时
         *  @parameter 2.延时多久，此处为秒级，还有纳秒等: 10ull * NSEC_PER_MSEC
         */
        
        __weak typeof(self)weakSelf = self;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
    
}
- (IBAction)getPhone:(id)sender {
    
    NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"tel:%@",telephoneString];
    
    UIWebView * callWebview = [[UIWebView alloc] init];
    
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    
    [self.view addSubview:callWebview];
    
}
- (IBAction)getCarType:(id)sender {
    
    UIButton * button = sender;
    if (button.tag == 1) {
        
        isFirst = 1;
        stateStr = @"全款车";
        [_quanKuanBtn setImage:[UIImage imageNamed:@"tuoyuan"] forState:UIControlStateNormal];
        [_daiKuanBtn setImage:[UIImage imageNamed:@"tuoyuan_nor"] forState:UIControlStateNormal];
    }else{
        
        isFirst = 2;
        stateStr = @"贷款车";
        [_quanKuanBtn setImage:[UIImage imageNamed:@"tuoyuan_nor"] forState:UIControlStateNormal];
        [_daiKuanBtn setImage:[UIImage imageNamed:@"tuoyuan"] forState:UIControlStateNormal];
    }
    
}

-(void)selecteCellAtIndex:(NSInteger)selectedIndex andType:(NSInteger)type{
    
    if (type == 0) {
        
        cId = [self.cityIdArray objectAtIndex:selectedIndex];
        NSString * nameStr = [self.cityNameArray objectAtIndex:selectedIndex];
        _cityLabel.text = nameStr;
        
        telephoneString = [self.telephoneArray objectAtIndex:selectedIndex];
        
        NSString * telephoneStr = [NSString stringWithFormat:@"请添加正确的借款人信息，以免耽误审核进度，如有任何疑问请拨打:%@",telephoneString];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:telephoneStr];
        NSRange range1 = [[str string] rangeOfString:@"请添加正确的借款人信息，以免耽误审核进度，如有任何疑问请拨打:"];
        [str addAttribute:NSForegroundColorAttributeName value:RGBCOLOR(153, 153, 153) range:range1];
        NSRange range2 = [[str string] rangeOfString:telephoneString];
        [str addAttribute:NSForegroundColorAttributeName value:RGBCOLOR(99, 146, 274) range:range2];
        _remarkLabel.attributedText =str;
        
    }else{
        NSString * nameStr = [self.periodArray objectAtIndex:selectedIndex];
        _periodTF.text = nameStr;
    }
    
}


//图片上传t功能
- (void)loadPic{
    
    addBut = [UIButton buttonWithType:UIButtonTypeCustom];
    addBut.frame = CGRectMake(20, 50, (SCREEN_WIDTH - 80)/3, (SCREEN_WIDTH - 80)/3);
    [addBut setBackgroundImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    addBut.layer.cornerRadius = 5;
    [addBut addTarget:self action:@selector(addPicAction:) forControlEvents:UIControlEventTouchUpInside];
    [_picView addSubview:addBut];
    
    
}
- (void)changePic{
    
    for (UIView *view in _picView.subviews) {
        
        if ([view isKindOfClass:[PS_PhotoView class]]) {
            [view removeFromSuperview];
        }
    }
    
    if (self.imageUrlArray > 0) {
        
        if (self.imageUrlArray.count >2) {
            
            _height_picView.constant = 50 + (SCREEN_WIDTH - 80)/3*2 +40;
            _height_backView.constant = 800 - 160 + 50 + (SCREEN_WIDTH - 80)/3*2 +40;
            
        }else{
            
            _height_picView.constant = 50+(SCREEN_WIDTH - 80)/3+20;
        }
        
        if (self.imageUrlArray.count == 5) {
            
            addBut.hidden = YES;
        }else{
            addBut.hidden = NO;
        }
        
        for (int i = 0; i<self.imageUrlArray.count +1; i++) {
            
            float w = (SCREEN_WIDTH - 80)/3;
            float lineNum = i/3;//行数
            float lieNum = i%3;
            
            if (i == self.imageUrlArray.count) {
                
                addBut.frame = CGRectMake(20+(w+20)*lieNum, 50+(w+20)*lineNum, w, w);
                
            }else{
                
                PS_PhotoView *photoView =[[PS_PhotoView alloc]initWithFrame:CGRectMake(20+(w+20)*lieNum, 50+(w+20)*lineNum, w, w)];
                photoView.backgroundColor = [UIColor clearColor];
                [photoView.picImage sd_setImageWithURL:[NSURL URLWithString:[self.imageUrlArray objectAtIndex:i]]];
                photoView.tag = i+50;;
                photoView.deleteBtn.tag = i+50;
                photoView.tap.view.tag = i+50;
                photoView.delegate = self;
                photoView.deletePhotoDelegate = self;
                [_picView addSubview:photoView];
                
            }
            
        }
        
    }else{
        
        addBut.hidden = NO;
        addBut.frame = CGRectMake(20, 50, (SCREEN_WIDTH - 80)/3, (SCREEN_WIDTH - 80)/3);
    }
    
}
- (void)addPicAction:(UIButton *)sender{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择获取图片的方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePicker = [[UIImagePickerController alloc] init];
        self->_imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self->_imagePicker.delegate = self;
        self->_imagePicker.allowsEditing = YES;
        [self presentViewController:self->_imagePicker animated:YES completion:nil];
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 - self.imageUrlArray.count delegate:self];
        
        [self presentViewController:self->imagePickerVc animated:YES completion:nil];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消");
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
    
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    [self uploadImage:image];
    
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark -TZImagePickerDelegate
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets{
    
    id obj = assets[0];
    [self.imageArray removeAllObjects];
    NSMutableArray * pArr =  [NSMutableArray arrayWithArray:photos];
    self.imageArray= pArr;
    if (self.imageArray>0) {
        
        for (int i =0; i<self.imageArray.count; i++) {
            
            UIImage * image = [self.imageArray objectAtIndex:i];
            [self uploadImage:image];
        }
    }
    
}

- (void)uploadImage:(UIImage *)image{
    
    NSData *data = UIImageJPEGRepresentation(image, 0.1);
    
    NSString *encodedImageStr = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",[data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
    
    [Utils post:UPLOADIMG parameters:@{@"uid":USERID,@"avatars":encodedImageStr} success:^(NSInteger recode, id jsonObject) {
        
        NSString * dataUrl = [jsonObject objectForKey:@"data"];
        [self.imageUrlArray addObject:dataUrl];
        [self changePic];
        NSLog(@"json=%@",jsonObject);
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}
- (void)getSubProductData{
    
    [Utils post:GETSUBPRODUCT parameters:@{@"sub_pid":_subPID} success:^(NSInteger recode, id jsonObject) {
        NSDictionary * dataDic = [jsonObject objectForKey:@"data"];
        self->periodArr = [dataDic objectForKey:@"period"];
        self->cityArr = [dataDic objectForKey:@"city2"];
        if (self->cityArr.count>0) {
            
            for (int i =0; i<self->cityArr.count; i++) {
                
                NSDictionary * dic = [self->cityArr objectAtIndex:i];
                NSString *idStr = [dic objectForKey:@"id"];
                [self.cityIdArray addObject:idStr];
                NSString * nameStr = [dic objectForKey:@"name"];
                [self.cityNameArray addObject:nameStr];
                NSString * telephone = [dic objectForKey:@"telephone"];
                [self.telephoneArray addObject:telephone];
            }
            
            if (self->cityArr.count == 1) {
                
                self->_c_rightArrow.hidden = YES;
                self->_trailing_CityLabel.constant = 20;
                self->_cityLabel.text = [self.cityNameArray firstObject];
                self->cId = [self.cityIdArray firstObject];
                self->telephoneString = [self.telephoneArray firstObject];
                
                NSString * telephoneStr = [NSString stringWithFormat:@"请添加正确的借款人信息，以免耽误审核进度，如有任何疑问请拨打:%@",self->telephoneString];
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:telephoneStr];
                NSRange range1 = [[str string] rangeOfString:@"请添加正确的借款人信息，以免耽误审核进度，如有任何疑问请拨打:"];
                [str addAttribute:NSForegroundColorAttributeName value:RGBCOLOR(153, 153, 153) range:range1];
                NSRange range2 = [[str string] rangeOfString:self->telephoneString];
                [str addAttribute:NSForegroundColorAttributeName value:RGBCOLOR(99, 146, 274) range:range2];
                self->_remarkLabel.attributedText =str;
                
            }else{
                self->_c_rightArrow.hidden = NO;
                self->_trailing_CityLabel.constant = 37;
            }
            
        }
        
        if (self->periodArr.count>0) {
            
            for (int i =0; i<self->periodArr.count; i++) {
                
                NSDictionary * dic = [self->periodArr objectAtIndex:i];
                NSString * nameStr = [dic objectForKey:@"name"];
                [self.periodArray addObject:nameStr];
                
            }
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}


//删除图片
- (void)deletePhoto:(NSInteger)index{
    
    NSInteger deleteTag = index - 50;
    
    if (self.imageUrlArray.count > deleteTag) {
        
        [self.imageUrlArray removeObjectAtIndex:deleteTag];
        
        [self changePic];
    }
    
    
}
//浏览
- (void)photoViewSelectedIndex:(NSInteger)index{
    
    NSInteger seletedPhoto = index-50;
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    browser.sourceImagesContainerView = _picView;
    browser.imageCount = self.imageUrlArray.count;
    browser.currentImageIndex = seletedPhoto;
    browser.delegate = self;
    [browser show];
}
#pragma mark - SDPhotoBrowserDelegate

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    
    NSString *str = self.imageUrlArray[index];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    
    __block UIImage *_image;
    [imageView sd_setImageWithURL:[NSURL URLWithString:str] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        _image = image;
    }];
    return _image;
}

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    
    NSString *str = self.imageUrlArray[index];
    
    NSURL *url = [NSURL URLWithString:str];
    return url;
}

- (void)textFieldDidChange:(UITextField *)textField

{
    
    if (textField == _phoneTF) {
        
        if (textField.text.length > 11) {
            
            textField.text = [textField.text substringToIndex:11];
            
        }
        
    }
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
